<template>
  <div class="main">
    <el-form :model="loginForm" status-icon ref="loginForm" size="default" label-width="0" class="login-form">
      <el-form-item 
        label="" 
        prop="username"
        :rules="[
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ]">
        <el-input 
          type="text"
          v-model="loginForm.username"
          autocomplete="off"
          prefix-icon="el-icon-user"
          placeholder="请输入账号"></el-input>
      </el-form-item>
      <el-form-item 
        label=""
        :rules="[
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]">
        <el-input 
        type="password"
        v-model="loginForm.password"
        autocomplete="off"
        prefix-icon="el-icon-key"
        placeholder="请输入密码"></el-input>
      </el-form-item>
      <el-form-item>
        <el-checkbox v-model="rememberMe">自动登录</el-checkbox>
        <router-link
          to="/"
          class="forge-password"
          style="float: right;"
        >忘记密码</router-link>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="login-button" :loading="state.loginBt" @click="handleSubmit()">登陆</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { mapActions } from 'vuex'
import { timeFix } from '@/utils/util'

export default {
  name: 'Login',
  data () {
    return {
      loginForm: {
        username: 'admin@test.com',
        password: 'secret'
      },
      state: {
        loginBtn: false,
      },
      rememberMe: false
     }
  },
  methods: {
    ...mapActions(['Login', 'Logout']),
    handleSubmit() {
      this.state.loginBtn = true
      this.$refs['loginForm'].validate((valid) => {
        if (valid) {
          this.Login(this.loginForm)
            .then((res) => this.loginSuccess(res))
            .catch(err => this.requestFailed(err))
            .finally(() => {
              this.state.loginBtn = false
            })
        } else {
          setTimeout(() => {
            this.state.loginBtn = false
          }, 600)
        }
      })
    },
    loginSuccess () {
      this.$router.push({ name: 'home' })
      // 延迟 1 秒显示欢迎信息
      setTimeout(() => {
        this.$notify({
          type: 'success',
          title: '欢迎',
          message: `${timeFix()}，欢迎回来`
        })
      }, 1000)
    },
    requestFailed (err) {
      this.$notify.error({
        title: '提示',
        message: (err || {}).message || '请求出现错误，请稍后再试'
        // message: (((err.response || {}).data || {}).data || {}).message || '请求出现错误，请稍后再试'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.login-form {
  margin-top: 60px;
}
.login-button {
  width: 100%;
}
.forge-password {
  font-size: 14px;
}
</style>
